<?php
require_once 'Smarty/Smarty.class.php';

class App_View_Smarty extends Zend_View_Abstract
{
    /**
     * Smarty object
     *
     * @var App_Smarty
     */
    protected $_smarty = null;

    /**
     * Constructor
     *
     * @ Param array $config Configuration data
     */
    public function __construct($config = array())
    {
        $this->_smarty = new Smarty();

        foreach ($config['params'] as $key => $value) {
            if ('plugins_dir' === $key) {
                $this->_smarty->plugins_dir[] = $value;
            } else {
                $this->_smarty->$key = $value;
            }
        }

        $this->_smarty->template_dir = $config['scriptPath'];

        // Path to the helpers
        foreach ($config['helperDirs'] as $path => $prefix) {
            $this->addHelperPath($path, $prefix);
        }

        parent::__construct($config);
    }

    /**
     * Returns an object Smarty
     *
     * @ Return App_Smarty
     */
    public function getEngine()
    {
        return $this->_smarty;
    }

    /**
     * fetch a template, echos the result,
     *
     * @see Zend_View_Abstract::render()
     * @see Zend_View_Abstract::getVars()
     * @param string $name the template
     * @return void
     */
    protected function _run()
    {
        $this->strictVars(true);
        //force strict handling of variables

        foreach ($this->getVars() as $key => $value) {
            //for all the variables assigned to the view
            $this->_smarty->assign($key, $value);
        }
        //assign variables to the template engine

        $this->_smarty->assign_by_ref('this', $this);
        //why 'this'?
        //to emulate standard zend view functionality
        //doesn't mess up smarty in any way

        $this->_smarty->_v = $this;

        $paths = $this->getScriptPaths();  //edited by joelhy
        $path = array_shift($paths);
        //the path where templates are located

        $file = substr(func_get_arg(0), strlen($path));
        //smarty needs a template_dir, and can only use templates found in that
        //directory, so we have to strip it from the filename

        if (strstr($file, '/')) {
            //if file is in subdir, update template path
            $path .= substr($file, 0, strrpos($file, '/')) . '/';
            //update path to include any dirs in $file
            $file = substr($file, strrpos($file, '/') + 1);
            //update $file to _not_ include those dirs
        }
        //update the path and file, to comply with smarty's {include} usage

        $this->_smarty->template_dir = $path;
        //set the template directory
        $compileID = md5($path . $file);
        //a unique compile ID (in case of multiple templates by the same name)
        echo $this->_smarty->fetch($file, null, $compileID);
        //process the template (and filter the output)
    }
}